<template>
  <div style="overflow-x: auto; position: relative; height: calc(100vh - 140px); padding-bottom: 20px;">
    <!-- 用户表格 -->
    <el-table
        :data="pagedData"
        border
        style="min-width: 1200px;"
        v-loading="loading"
        size="small"
        :row-style="{ height: '45px' }"
        :cell-style="{ padding: '5px 0' }"
    >
      <el-table-column prop="id" label="ID" width="60" header-align="center" align="center" />
      <el-table-column prop="studentId" label="学号" width="110" header-align="center" align="center" />
      <el-table-column prop="username" label="姓名" width="80" header-align="center" align="center" />
      <el-table-column prop="nickname" label="昵称" width="80" header-align="center" align="center" />
      <el-table-column prop="password" label="密码" width="100" header-align="center" align="center" />
      <el-table-column prop="sex" label="性别" width="60" header-align="center" align="center">
        <template #default="{ row }">{{ row.sex === 1 ? '男' : '女' }}</template>
      </el-table-column>
      <el-table-column prop="phone" label="电话" width="110" header-align="center" align="center" />
      <el-table-column prop="email" label="邮箱" width="180" header-align="center" align="center" />
      <el-table-column prop="qq" label="QQ号" width="100" header-align="center" align="center" />
      <el-table-column prop="idCard" label="身份证号" width="140" header-align="center" align="center" />
      <el-table-column prop="photo" label="照片" width="80" header-align="center" align="center">
        <template #default="{ row }">
          <el-image
            v-if="row.photo"
            :src="row.photo"
            style="width: 30px; height: 30px; border-radius: 4px;"
            fit="cover"
            :preview-src-list="[row.photo]"
          />
          <span v-else style="color: #ccc;">无照片</span>
        </template>
      </el-table-column>
      <el-table-column prop="signature" label="座右铭" width="150" header-align="center" align="center" />
      <el-table-column prop="introduction" label="介绍" width="400" header-align="center" align="center" />
      <el-table-column prop="isactive" label="激活状态" width="80" header-align="center" align="center">
        <template #default="{ row }">
          <el-tag :type="row.isactive === 1 ? 'success' : 'danger'" size="small">
            {{ row.isactive === 1 ? '激活' : '未激活' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="lastUpdate" label="更新时间" width="140" header-align="center" align="center">
        <template #default="{ row }">
          {{ row.lastUpdate ? new Date(row.lastUpdate).toLocaleDateString() : '-' }}
        </template>
      </el-table-column>

      <!-- 操作列 -->
      <el-table-column label="操作" width="120" fixed="right" header-align="center">
        <template #default="scope">
          <div style="display: flex; justify-content: space-between;">
            <el-button type="text" size="small" @click="handleEdit(scope.row)">修改</el-button>
            <el-button type="text" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>


    <div>
      <!-- 编辑对话框 -->
      <el-dialog
          title="编辑学生信息"
          v-model="editDialogVisible"
          width="600px"
      >
        <el-form :model="editForm">
          <el-form-item label="学号" prop="studentId">
            <el-input v-model="editForm.studentId" disabled />
          </el-form-item>
          <el-form-item label="姓名" prop="username">
            <el-input v-model="editForm.username" />
          </el-form-item>
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="editForm.nickname" />
          </el-form-item>
          <el-form-item label="座右铭" prop="signature">
            <el-input v-model="editForm.signature" />
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-select v-model="editForm.sex" placeholder="请选择">
              <el-option label="男" value=1 />
              <el-option label="女" value=0 />
            </el-select>
          </el-form-item>
          <el-form-item label="介绍" prop="introduction">
            <el-input v-model="editForm.introduction" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email" />
          </el-form-item>
          <el-form-item label="电话" prop="phone">
            <el-input v-model="editForm.phone" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveEdit">保存</el-button>
        </div>
      </el-dialog>
    </div>


<!-- 分页器 -->
    <div style="position: fixed; right: 20px; bottom: 20px; z-index: 1000; background: white; padding: 10px; border-radius: 4px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
      <el-pagination
          background
          layout="prev, pager, next, jumper"
          :page-size="pageSize"
          :total="filteredData.length"
          v-model:current-page="currentPage"
          @current-change="handlePageChange"
          small
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { searchName } from '../store/useSearch'
import { getAllStudents , deleteStudent,updateStudent} from '../api/student'
import { ElMessage } from 'element-plus'

const editDialogVisible = ref(false)
const editForm = ref({})
// 学生数据
const tableData = ref([])
const loading = ref(false)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)

const handleEdit = (row) => {
  editForm.value = { ...row } // 将选中行的数据赋值给编辑表单
  editDialogVisible.value = true // 打开对话框
}

// 保存修改
const saveEdit = async () => {
  try {
    const updatedFields = Object.keys(editForm.value).reduce((acc, key) => {
      if (editForm.value[key] !== null && editForm.value[key] !== undefined) {
        acc[key] = editForm.value[key]
      }
      return acc
    }, {})

    const response = await updateStudent(updatedFields)
    if (response ) {
      ElMessage.success('修改成功')
      editDialogVisible.value = false // 关闭对话框
      fetchStudents() // 重新获取学生数据以更新表格
    } else {
      ElMessage.error('修改失败')
    }
  } catch (error) {
    console.error('修改学生失败:', error)
    ElMessage.error('修改学生失败')
  }
}
// 获取学生数据
const fetchStudents = async () => {
  loading.value = true
  try {
    const response = await getAllStudents()
    tableData.value = response.data || response || []
    console.log('获取学生数据:', tableData.value)
  } catch (error) {
    console.error('获取学生数据失败:', error)
    ElMessage.error('获取学生数据失败')
    tableData.value = []
  } finally {
    loading.value = false
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchStudents()
})

// 过滤后的数据
const filteredData = computed(() => {
  const keyword = searchName.value.trim().toLowerCase()
  if (!keyword) return tableData.value
  return tableData.value.filter(item =>
    (item.username && item.username.toLowerCase().includes(keyword)) ||
    (item.nickname && item.nickname.toLowerCase().includes(keyword)) ||
    (item.introduction && item.introduction.toLowerCase().includes(keyword))
  )
})

// 搜索时重置页码
watch(searchName, () => {
  currentPage.value = 1
})

// 当前页数据
const pagedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredData.value.slice(start, end)
})

// 操作按钮
const handleDelete = async (row) => {
  try {
    const confirmDelete = window.confirm(`确定要删除学生：${row.username} (学号: ${row.studentId}) 吗？`)
    if (!confirmDelete) return

    const response = await deleteStudent(row.studentId)
    console.log('删除操作返回值:', response) // 打印后端返回值

    // 后端返回boolean值，true表示删除成功
    if (response === true) {
      ElMessage.success('删除成功')
      console.log('删除成功') // 打印成功日志
      fetchStudents() // 重新获取学生数据以更新表格
    } else {
      ElMessage.error('删除失败')
      console.log('删除失败') // 打印失败日志
    }
  } catch (error) {
    console.error('删除学生失败:', error)
    ElMessage.error('删除学生失败')
  }
}
const handlePageChange = (page) => {
  currentPage.value = page
}

// 暴露方法给父组件调用
defineExpose({
  fetchStudents
})
</script>

<style scoped>
.el-table th {
  text-align: center;
}
</style>
